package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Reference
    private MenuService menuService;

	@RequestMapping("/loginSuccess")
	public String loginSuccess(){
		return "redirect:http://localhost:83/pages/main.html";
	}

	@RequestMapping("/loginFail")
	public String loginFail(){
		return "redirect:http://localhost:83/login.html?error=true";
	}

	@RequestMapping("/getUsername")
	@ResponseBody
	public Result getUsername(){
		//从授权框架上下文获取授权对象，再从授权对象获取授权框架用户对象User,最后获取用户名
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		if(principal instanceof User){
			User user = (User) principal;
            String username = user.getUsername();
            List<Menu> menuList = menuService.findByUsername(username);
            log.debug("UserController: getUsername: menuList ===> " + menuList);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("username",username);
            map.put("menuList",menuList);
            log.debug("UserController: getUsername: map ===> " + map);
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS,map);
		}
		return new Result(false, MessageConst.GET_USERNAME_FAIL);
	}
}